<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.geping.etl.common.util.Constants" %>
<%@ page import="com.geping.etl.common.entity.Sys_UserAndOrgDepartment" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//北现开关
String bxSyn = (String) request.getSession().getAttribute("bxSyn");
//当前登录用户信息
Sys_UserAndOrgDepartment sysUser = (Sys_UserAndOrgDepartment)request.getSession().getAttribute("sys_User");
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>角色分配</title>
    <%@include file="head.jsp"%>
</head>
<body class="easyui-layout">
<!-- 西 -->
<%--<div data-options="region:'west',split:true,title:'机构信息'" style="width:350px;padding: 10px">
		 <table class="easyui-datagrid" fitColumns="true" title="" id="dg1" data-options="singleSelect:true,rownumbers:false,autoRowHeight:false" style="height:440px">
		         <thead>
					<tr>
					    <th data-options="field:'id',width:80,align:'center',hidden:true">ID</th>
					    <th data-options="field:'orgName',width:80,align:'center'">机构名称</th>
						<th data-options="field:'orgId',width:80,align:'center'">机构代码</th>
					</tr>
				 </thead>
				 
				 <tbody>
					<c:forEach items="${orgList}" var="ol">
					  <tr>
						 <td>${ol.id}</td>
						 <td>${ol.orgName}</td>
			             <td>${ol.orgId}</td>
					 </tr>
				   </c:forEach>
		       </tbody>
	    </table> 
</div>--%>

     
<!-- 中 -->
<div data-options="region:'center',title:'用户角色分配'" style="width:650px">
	         <table class="easyui-datagrid" fitColumns="true" title="" id="dg2" data-options="singleSelect:true,rownumbers:true,toolbar:'#tb',autoRowHeight:false,pagination:true,pageSize:30" style="height: 440px;">
		         <thead>
					<tr>
					    <th data-options="field:'id',width:80,align:'center',hidden:true">ID</th>
					    <th data-options="field:'loginid',width:80,align:'center'">登录账号</th>
						<th data-options="field:'usercname',width:80,align:'center'">用户中文名</th>
					<%--	<th data-options="field:'orgid',width:80,align:'center'">机构代码</th>--%>
						<th data-options="field:'departmentname',width:80,align:'center'">部门名称</th>
					</tr>
				</thead>
				
				<tbody>
					<c:forEach items="${organduserList}" var ="oaul">
					<tr>
						 <td>${oaul.id}</td>
						 <td>${oaul.loginid}</td>
						 <td>${oaul.usercname}</td>
			       <%--      <td>${oaul.orgid}</td>--%>
			             <td>${oaul.departmentname}</td>
					 </tr>
					</c:forEach>
				</tbody>
	         </table>
	
			<div id="tb" style="padding:5px;height:auto;">
				登录账号:
					<input type="text" style="width:173px;height:21px" id="loginid" name="loginid">&nbsp;&nbsp;
				    <a class="easyui-linkbutton" iconCls="icon-search" onclick="selectRecordByLoginID()">查询</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
				<%
					if((Constants.BX_SYN_USER_ON.equals(bxSyn) && "admin".equals(sysUser.getLoginid())) || !Constants.BX_SYN_USER_ON.equals(bxSyn)){
				%>
					<a class="easyui-linkbutton" iconCls="icon-edit"  onclick="AssignRole()">角色分配</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
				<%
					}
				%>

			</div>
</div>

	<!-- 角色分配 -->
	<div style="visibility: hidden;">
		<div id="AssignRoleForDialog" class="easyui-dialog" title="角色分配" data-options="iconCls:'icon-save',toolbar:'#tbForAssignRole'" style="width: 800px; height: 510px;padding: 10px">
			<div id="tbForAssignRole">
				<a class="easyui-linkbutton" data-options="iconCls:'icon-save'" onclick="saveForAssignRole()">保存</a>&nbsp;&nbsp;
				<a class="easyui-linkbutton" data-options="iconCls:'icon-undo'" onclick="cancel()">取消</a>
			</div>
    
                                  系统名称:<input class="easyui-combobox" name="subjectId" id="subjectId" data-options="valueField:'id',textField:'text',editable:false" style="height: 21px;width: 173px">
           
			<table id="AssignRoleForTable" class="easyui-datagrid" fitColumns="true" style="width:760px;height:400px;padding-top: 10px" data-options="checkOnSelect:true,autoRowHeight:false,pagination:true,rownumbers:true,idField:'id',pageSize:50">
				<thead>
						<tr>
							<th field="ck" checkbox="true"></th>
							<th data-options="field:'id',width:230,align:'center',hidden:true"></th>
							<th data-options="field:'roleName',width:230,align:'center'">角色名称</th>
							<th data-options="field:'description',width:230,align:'center'">角色描述</th>
						</tr>
			   </thead>
		   </table>
	   </div>
   </div>




<!--------------------------------------------------js ------------------------------------------------------------------------------->	
<script type="text/javascript">
   //声明选中行的rowId
   var roleId;
   var userId;


    //初始化弹出框默认关闭
  	$(function(){
  		$('#AssignRoleForDialog').dialog('close');
  		//为数据网格分页
		$('#dg2').datagrid({loadFilter:pagerFilter1, fit: true});
		$('#dg2').datagrid('getPager').pagination({ //设置分页功能栏
			//分页功能可以通过Pagination的事件调用后台分页功能来实现
			onRefresh: function () {
				selectRecordByLoginID();
			}
		});

		$('#AssignRoleForTable').datagrid({loadFilter:pagerFilter});
  		
  		
  		//机构信息中的单击事件
  		$("#dg1").datagrid({
  	        onClickRow : function(index, row){
  	               $.ajax({
  	            	    url : 'findUserOrgDepartmentByOrgId',
  					    type : 'POST', //GET
  					    async : true, //或false,是否异步
  					    contentType:'application/x-www-form-urlencoded; charset=UTF-8',
  					    data:{"orgId":row.orgId,"randSession":"${authId}"},
  					    dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
  					    success : function(data){
  					    	var userOrgDepartmentList = data.userOrgDepartmentList;
  					    	var userOrgDepartmentArray = [];
  					    	for(var i = 0;i<userOrgDepartmentList.length;i++){
  					    		userOrgDepartmentArray.push({
  					    			'id':userOrgDepartmentList[i].id,
  								    'loginid':userOrgDepartmentList[i].loginid,
									<c:if test="${sessionScope.user_more_org == 'on'}">
									'orgid':data.orgId,
									</c:if>
									<c:if test="${sessionScope.user_more_org != 'on'}">
									'orgid':userOrgDepartmentList[i].orgid,
									</c:if>
  									'usercname':userOrgDepartmentList[i].usercname,
  									'departmentname':userOrgDepartmentList[i].departmentname
  					    		});
  					    	}
  					    	$("#dg2").datagrid('loadData',userOrgDepartmentArray);
  					    }
  	               })
  	        }
  	    });
  		
  		
  		//系统名称combobox选中事件
  		$('#subjectId').combobox({
  			onSelect:function(record){
  				 $.ajax({
  					url : 'getSysAuthRole_roleNameAndDescription',
  					type : 'POST', //GET
  					async : true, //或false,是否异步
  					contentType:'application/x-www-form-urlencoded; charset=UTF-8',
  					data:{"userId":userId,"subjectId":record.id,"randSession":"${authId}"},
  					dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
  					success : function(data){
  						//显示用户角色分配的数据
  						//$('#AssignRoleForTable').datagrid('loadData', { total: 0, rows: [] });
  						var assignrole = [];
  						for(var i =0;i<data.list.length;i++){
  							assignrole.push({
  								'id' : data.list[i].id,
  								'roleName' : data.list[i].roleName,
  								'description' : data.list[i].description
  							});
  					    } 
  						$('#AssignRoleForTable').datagrid('loadData',assignrole);
  					 
  						
  						$('#AssignRoleForTable').datagrid('unselectAll');
  						//回显已经分配的角色名称和角色描述
  						var sysAuthRoleUserList = data.sysAuthRoleUserList;
  						//获取分配角色网格中的所有数据
  						var assignRoleArray = $('#AssignRoleForTable').datagrid('getRows');
  						for (var i = 0; i < sysAuthRoleUserList.length; i++) {
  								for(var j = 0;j<assignRoleArray.length;j++){
  									if(sysAuthRoleUserList[i].roleId == assignRoleArray[j].id){
  										$('#AssignRoleForTable').datagrid('selectRow',j);
  									}
  								}
  						}
  						
  						var jsonStr = '[{"id":"all","text":"全部"},';
  						var subjectList = data.subjectList;
  						var sujbectListLength = data.subjectList.length;
  						for(var i =0;i<data.subjectList.length;i++){
  							if(i == (sujbectListLength - 1)){
  								jsonStr = jsonStr + '{"id":"'+subjectList[i].id+'",'+'"text":"'+subjectList[i].subjectName+'"}'
  							}else{
  								jsonStr = jsonStr + '{"id":"'+subjectList[i].id+'",'+'"text":"'+subjectList[i].subjectName+'"},'
  							}
  					    }
  						jsonStr = jsonStr + ']';
  						var jsonObj = JSON.parse(jsonStr);     //将json格式的字符串转为json对象
  						$("#subjectId").combobox("loadData",jsonObj);
  					}
  			  });
  			}
  		});
	});

	var sysAuthRoleUserListGlobal = "";
	//分页
	function pagerFilter(data) {
		if (typeof data.length == 'number' && typeof data.splice == 'function') { // is array
			data = {
				total : data.length,
				rows : data
			}
		}
		var dg = $(this);
		var opts = dg.datagrid('options');
		var pager = dg.datagrid('getPager');
		pager.pagination({
			onSelectPage : function(pageNum, pageSize) {
				opts.pageNumber = pageNum;
				opts.pageSize = pageSize;
				pager.pagination('refresh', {
					pageNumber : pageNum,
					pageSize : pageSize
				});
				dg.datagrid('loadData', data);
				//获取分配角色网格中的所有数据
				var assignRoleArray = $('#AssignRoleForTable').datagrid('getRows');
				for (var i = 0; i < sysAuthRoleUserListGlobal.length; i++) {
					for(var j = 0;j<assignRoleArray.length;j++){
						if(sysAuthRoleUserListGlobal[i].roleId == assignRoleArray[j].id){
							$('#AssignRoleForTable').datagrid('selectRow',j);
						}
					}
				}
			}
		});
		if (!data.originalRows) {
			data.originalRows = (data.rows);
		}
		var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
		var end = start + parseInt(opts.pageSize);
		data.rows = (data.originalRows.slice(start, end));
		return data;
	}

   function pagerFilter1(data){
	   if (typeof data.length == 'number' && typeof data.splice == 'function'){	// is array
		   data = {
			   total: data.length,
			   rows: data
		   }
	   }
	   var dg = $(this);
	   var opts = dg.datagrid('options');
	   var pager = dg.datagrid('getPager');
	   pager.pagination({
		   onSelectPage:function(pageNum, pageSize){
			   opts.pageNumber = pageNum;
			   opts.pageSize = pageSize;
			   pager.pagination('refresh',{
				   pageNumber:pageNum,
				   pageSize:pageSize
			   });
			   dg.datagrid('loadData',data);
		   }
	   });
	   if (!data.originalRows){
		   data.originalRows = (data.rows);
	   }
	   var start = (opts.pageNumber-1)*parseInt(opts.pageSize);
	   var end = start + parseInt(opts.pageSize);
	   data.rows = (data.originalRows.slice(start, end));
	   return data;
   }
	
      
   //点击查询按钮
 function selectRecordByLoginID(){
	   var loginId = $("#loginid").val();
	   var randSession = "${authId}"
	   window.location.href='getUserAndOrgDepartmentByLikeLoginID?loginId='+ encodeURIComponent(loginId)+"&randSession="+randSession;
}
   
  
   //点击取消按钮
   function cancel() {
		$('#AssignRoleForDialog').dialog('close');
	}
   
  //点击角色分配按钮
  function AssignRole(){
	  var row = $("#dg2").datagrid('getSelected'); //获取选中行对象
	  var randSession = "${authId}"
	  if (row != null){
		  userId = row.id;
		  $.ajax({
				url : 'getSysAuthRole_roleNameAndDescription',
				type : 'POST', //GET
				async : true, //或false,是否异步
				contentType:'application/x-www-form-urlencoded; charset=UTF-8',
				data:{"userId":userId,"randSession":randSession},
				dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
				success : function(data){
					//显示用户角色分配的数据
					//$('#AssignRoleForTable').datagrid('loadData', { total: 0, rows: [] });
					var assignrole = [];
					for(var i =0;i<data.list.length;i++){
						assignrole.push({
							'id' : data.list[i].id,
							'roleName' : data.list[i].roleName,
							'description' : data.list[i].description
						});
				    }
					$('#AssignRoleForTable').datagrid('loadData',assignrole);

					$('#AssignRoleForTable').datagrid('unselectAll');
					//回显已经分配的角色名称和角色描述
					sysAuthRoleUserListGlobal = data.sysAuthRoleUserList;
					//获取分配角色网格中的所有数据
					var assignRoleArray = $('#AssignRoleForTable').datagrid('getRows');
					for (var i = 0; i < sysAuthRoleUserListGlobal.length; i++) {
							for(var j = 0;j<assignRoleArray.length;j++){
								if(sysAuthRoleUserListGlobal[i].roleId == assignRoleArray[j].id){
									$('#AssignRoleForTable').datagrid('selectRow',j);
								}
							}
					}

					var jsonStr = '[{"id":"all","text":"全部"},';
					var subjectList = data.subjectList;
					var sujbectListLength = data.subjectList.length;
					for(var i =0;i<data.subjectList.length;i++){
						if(i == (sujbectListLength - 1)){
							jsonStr = jsonStr + '{"id":"'+subjectList[i].id+'",'+'"text":"'+subjectList[i].subjectName+'"}'
						}else{
							jsonStr = jsonStr + '{"id":"'+subjectList[i].id+'",'+'"text":"'+subjectList[i].subjectName+'"},'
						}
				    }
					jsonStr = jsonStr + ']';
					var jsonObj = JSON.parse(jsonStr);     //将json格式的字符串转为json对象
					$("#subjectId").combobox("loadData",jsonObj);
				}
		  });

		  $('#subjectId').combobox('select','all');

		  $('#AssignRoleForDialog').dialog('open');
		  $('#AssignRoleForDialog').dialog({modal : true});
	  }else{
		  $.messager.alert('操作提示', '请选择一条数据分配角色', 'info');
	  }
  }
  
 //点击角色分配中的保存按钮
  function saveForAssignRole(){
	  var randSession = "${authId}"
	  var assignroleforsave = $('#AssignRoleForTable').datagrid('getSelections');
	  	   var biaoshi = '';
		   var jsonStr = '[' ;

			for (var i = 0; i < assignroleforsave.length; i++) {
				var id = assignroleforsave[i].id;
				biaoshi = '0';
			    jsonStr = jsonStr + '{"userId":"'+userId+'","roleId":"'+id+'","biaoshi":"'+biaoshi+'"}'
			}
			if(assignroleforsave.length==0){
				
				biaoshi = '1';
				jsonStr = jsonStr + '{"userId":"'+userId+'","roleId":"'+id+'","biaoshi":"'+biaoshi+'"}'
			}
			
			jsonStr = jsonStr.replace(/{/g,',{').replace(',','');
			jsonStr = jsonStr + ']';
			
			$.ajax({
				url : 'saveSys_Auth_Role_User',
				type : 'POST', //GET
				async : true, //或false,是否异步
				data : {"mydata":jsonStr,"randSession":randSession},
				dataType : 'json', //返回的数据格式：json/xml/html/script/jsonp/text
				
				success : function(data) {	
					if (data == '1') { 
						$.messager.alert('','保存成功','info',
						function(r) {
							window.location.href = "role_distribution";
						});
					} else {
						$.messager.alert('操作提示','保存失败','error');
					}
				}
		})
  }
/************************************************************************************************************************************/
/************************************************************************************************************************************/
/************************************************************************************************************************************/


</script>		
</body>
</html >
